from flask import jsonify, request
from . import api_bp, load_json_data
from config import Config
from mark_agent import mark_generator


@api_bp.route('/messages', methods=['GET'])
def get_messages():
    data = load_json_data(Config.JSON_FILES['messages'])
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    start = (page - 1) * per_page
    end = start + per_page

    # Check if token is provided in query parameters
    token = request.args.get('token')
    # 这里显示token为none，所以给token赋一个值
    #token = "abc123def456ghi789jk"
    #赋值结束
    if token:
        marked_data = []
        orginal_data = data[start:end]
        marked_data,mark_bits = mark_generator.mark_generate(orginal_data, token)
        return jsonify({
            "marked_data": marked_data,
            "mark_bits": mark_bits
        })

    return jsonify(data[start:end])


@api_bp.route('/messages/<int:message_id>', methods=['GET'])
def get_message(message_id):
    data = load_json_data(Config.JSON_FILES['messages'])
    message = next((item for item in data if item['messageId'] == message_id), None)

    if message:
        # Check if token is provided in query parameters
        token = request.args.get('token')
        if token:
            marked_data = []
            orginal_data = message
            marked_data,mark_bits = mark_generator.mark_generate(orginal_data, token)
            return jsonify({
                "marked_data": marked_data,
                "mark_bits": mark_bits
            })

        return jsonify(message)
    return jsonify({"error": "Message not found"}), 404